package cn.gson.boot.model.service;

import cn.gson.boot.model.dao.CompetitorDao;
import cn.gson.boot.model.dao.SalesDao;
import cn.gson.boot.model.mapper.CompetitorMapper;
import cn.gson.boot.model.pojos.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CompetitorService {
    @Autowired
    CompetitorMapper competitorMapper;
    @Autowired
    CompetitorDao competitorDao;
    @Autowired
    SalesDao salesDao;

    //竞争对手分页查询
    public List<Competitor> selectCompetitor(String search, String type,String empName) {
        return competitorMapper.selectCompetitors(search,type,empName);
    }

    //新增竞争对手
    public void addCompetitor(Competitor competitor) {
        competitor.setCompetitorSc(0);
        Sales sales = salesDao.findById(competitor.getSales().getSalesId()).get();
        int i = Integer.parseInt(sales.getSalesPossibility().substring(0,2));
        if(competitorMapper.selectSalesCompetitor(competitor.getSales().getSalesId()).size()==0){
            if(i<60){
                i = i+20;
                sales.setSalesPossibility(i+"%");
                salesDao.save(sales);
            }
        }
        competitorDao.save(competitor);
    }

    //查询需要修改的竞争对手
    public List<Competitor> upCompetitor(Integer competitorId) {
        return competitorMapper.upCompetitor(competitorId);
    }

    //删除竞争对手
    public void delCompetitor(Integer competitorId) {
        Competitor competitor = competitorDao.findById(competitorId).get();
        if(competitorMapper.selectSalesCompetitor(competitor.getSales().getSalesId()).size()==1){
            Sales sales = salesDao.findById(competitor.getSales().getSalesId()).get();
            int i = Integer.parseInt(sales.getSalesPossibility().substring(0,2));
            if(i>=30){
                i = i-20;
                sales.setSalesPossibility(i+"%");
            }
            salesDao.save(sales);
            competitor.setCompetitorSc(1);
            competitorDao.save(competitor);
        }else {
            competitor.setCompetitorSc(1);
            competitorDao.save(competitor);
        }
    }

    //客户列表
    public List<Kehu> selectKh(String khsearch,String empName) {
        return competitorMapper.selectKh(khsearch,empName);
    }

    //对应机会列表
    public List<Sales> selectSales(String khName) {
        return competitorMapper.selectSales(khName);
    }

    //查询竞争状态列表
    public List<ContendStatus> conList() {
        return competitorMapper.conList();
    }

    //销售机会页面已生成竞争对手不可删除
    public List<Competitor> selectSalesCompetitor(Integer salesId) {
        return competitorMapper.selectSalesCompetitor(salesId);
    }
}
